package com.stars.easyms.base.util;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.MutablePropertySources;

import java.util.Set;
import java.util.function.Consumer;

/**
 * <p>className: ApolloListenUtil</p>
 * <p>description: 自定义apollo监听工具类</p>
 *
 * @author guoguifang
 * @date 2019-08-26 17:33
 * @since 1.3.0
 */
public final class ApolloListenUtil {

    private static final String APOLLO_PROPERTY_SOURCES = "ApolloPropertySources";

    private static final String APOLLO_BOOTSTRAP_PROPERTY_SOURCES = "ApolloBootstrapPropertySources";

    public static void listen(ConfigurableApplicationContext applicationContext, Consumer<ConfigChangeEvent> consumer) {
        MutablePropertySources mutablePropertySources = applicationContext.getEnvironment().getPropertySources();
        if (mutablePropertySources.contains(APOLLO_PROPERTY_SOURCES) || mutablePropertySources.contains(APOLLO_BOOTSTRAP_PROPERTY_SOURCES)) {
            Config config = ConfigService.getAppConfig();
            if (config != null) {
                config.addChangeListener(consumer::accept);
            }
        }
    }

    public static void listenWithChangedKeys(ConfigurableApplicationContext applicationContext, Consumer<Set<String>> consumer) {
        MutablePropertySources mutablePropertySources = applicationContext.getEnvironment().getPropertySources();
        if (mutablePropertySources.contains(APOLLO_PROPERTY_SOURCES) || mutablePropertySources.contains(APOLLO_BOOTSTRAP_PROPERTY_SOURCES)) {
            Config config = ConfigService.getAppConfig();
            if (config != null) {
                config.addChangeListener(changeEvent -> consumer.accept(changeEvent.changedKeys()));
            }
        }
    }

    private ApolloListenUtil() {}

}